﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MuseLibrary.Packets
{
    public abstract class Packet : IPacket
    {
        public void ReadByte(int b)
        {
            _rawData.Add(b);

            if (_isFirstByte)
            {
                _isFirstByte = false;
                if (_canHaveFlags && b.DropLeadingBits(4) != 0)
                    _hasFlags = true;
            }

            if (_rawData.Count == Length)
                IsInitialised = true;
        }

        public virtual int Length
        {
            get
            {
                if (_length == 0)
                    throw new Exception("Packet's length is not initialised");

                return _length;
            }
            private set { _length = value; }
        }

        protected virtual void DoInitialisation()
        {

        }

        public bool IsInitialised
        {
            get { return _isInitialised; }
            private set
            {
                _isInitialised = value;
                if (_isInitialised) DoInitialisation();
            }
        }

        public List<int> RawData
        {
            get { return _rawData; }
        }

        public abstract PacketType Type { get; }

        public bool HasFlags
        {
            get { return _hasFlags; }
        }

        private bool _isFirstByte = true;
        protected bool _isInitialised;
        protected int _length = 0;
        protected List<int> _rawData = new List<int>();
        private bool _hasFlags;
        protected bool _canHaveFlags = true;
        protected bool _hasPostInitialisation = false;

        public virtual void PostInitialisation(int[] values)
        {

        }

        public bool HasPostInitialisation
        {
            get { return _hasPostInitialisation; }
        }

        public override string ToString()
        {
            return Type.ToString();
        }
    }
}
